package com.traffic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.constant.Status;
import com.traffic.entity.Message;
import com.traffic.mapper.MessageMapper;
import com.traffic.service.PushService;


import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.GroupPushClient;
import cn.jpush.api.push.GroupPushResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import io.netty.handler.codec.http.HttpMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.traffic.constant.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PushServiceImpl extends ServiceImpl<MessageMapper, Message> implements PushService {

    protected static final String APP_KEY = Const.APP_KEY;
    protected static final String MASTER_SECRET = Const.MASTER_SECRET;

//    protected static final String GROUP_PUSH_KEY = "";
//    protected static final String GROUP_MASTER_SECRET = "";

    protected static final Logger LOG = LoggerFactory.getLogger(PushService.class);

    @Autowired
    MessageMapper messageMapper;

    @Override
    public PushResult testSendPush(List<String> users,String content,String title) {


        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);

        final PushPayload payload = buildPushObject_ios(users,content,title);

        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            System.out.println(result);
            // 如果使用 NettyHttpClient，需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
            return result;
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }


        return null;
    }

    @Override
    public PushResult testSendPush(String content,String title) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);

        final PushPayload payload = buildAllPushObject_ios(content,title);

        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            System.out.println(result);
            // 如果使用 NettyHttpClient，需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
            return result;
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }


        return null;
    }

    public static PushPayload buildPushObject_ios(List<String> users,String content,String title) {
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("test", Const.JIGUANG_API);
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(users))
                .setNotification(Notification.newBuilder()
                        .setAlert(title+"\n"+content)
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("test",extras.get("test")).build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false).build())
                .build();
    }


    public static PushPayload buildAllPushObject_ios(String content,String title) {
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("test", Const.JIGUANG_API);
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .setAlert(title+"\n"+content)
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("test", extras.get("test")).build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false).build())
                .build();
    }

    @Override
    public List<Message> searchList(String startDate, String endDate, String content) throws ParseException {

        startDate = startDate.replace("Z"," UTC");
        endDate = endDate.replace("Z"," UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date stime = new Date();
        Date etime =new Date();

        if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            stime = format.parse(startDate);
            etime = format.parse(endDate);
        }
        else{
            stime = format.parse("2020-01-14T00:00:00.000 UTC");
            etime = format.parse("2030-01-14T00:00:00.000 UTC");
        }
        final String sresult = defaultFormat.format(stime);
        final String eresult = defaultFormat.format(etime);

        QueryWrapper<Message> wrapper = new QueryWrapper<>();

        //  wrapper.like("question",ques).between("create_time",startDate,endDate);
        wrapper.and(messageQueryWrapper ->messageQueryWrapper.like("content",content).or().like("title",content)).
                and(StringUtils.isNotBlank(startDate)
                                && StringUtils.isNotBlank(endDate),
                        dateSql ->dateSql.between("createtime",sresult,eresult)).orderByDesc("createtime");

        List<Message> messages = messageMapper.selectList(wrapper);

        return messages;
    }
}
